<template>
	<view class="app-container">
		<view class="top-nav">
			<text class="nav-item" :class="{ 'active': currentTab === '要闻' }" @click="currentTab = '要闻'">要闻</text>
			<text class="nav-item" :class="{ 'active': currentTab === '推荐' }" @click="currentTab = '推荐'">推荐</text>
			<text class="nav-item" :class="{ 'active': currentTab === '关注流' }" @click="currentTab = '关注流'">关注流</text>
			<text class="nav-item" :class="{ 'active': currentTab === '24小时' }" @click="currentTab = '24小时'">24小时</text>
			<text class="nav-item" :class="{ 'active': currentTab === '娱乐' }" @click="currentTab = '娱乐'">娱乐</text>
			<text class="nav-item" :class="{ 'active': currentTab === '泉州' }" @click="currentTab = '泉州'">泉州</text>
			<text class="nav-item" :class="{ 'active': currentTab === '财经' }" @click="currentTab = '财经'">财经</text>
		</view>
		<view class="weather-search">
			<view class="weather-info" v-if="weatherData.length >= 2">
				<text>明日：{{ cityInfo.parent }} {{ cityInfo.city }} {{ weatherData[1].ymd }} {{ weatherData[1].week }} {{ weatherData[1].high }} {{ weatherData[1].low }} </text>
			</view>
			<view class="search-box">
				<text class="search-placeholder">搜索关键词</text>
			</view>
		</view>
		<view class="update-tip" v-if="showUpdateTip" :class="{ 'fade-out': isFading }">
			<text>为您更新了{{ updateCount }}条内容</text>
		</view>
		<view class="news-list">
			<view class="loading" v-if="isLoading">
				<text>加载中...</text>
			</view>
			<view class="empty" v-if="!isLoading && newsList.length === 0">
				<text>暂无新闻数据</text>
			</view>
			<view v-for="(item, index) in newsList" :key="item.nid" class="list-item">
				<NewsCardView :nid="item.nid" :title="item.title" :mode="item.mode" :isTop="item.isTop"
					:author="item.author" :comments="item.comments" :time="item.time" :images="item.images"
					:content="item.content" :showSearch="item.showSearch" :bgColor="item.bgColor">
					<template v-slot:tips>
						<view class="slot-content">
							<text class="search-label">搜索：</text>
							<view class="search-tag" v-for="(tag, i) in item.searchTags" :key="i">
								<text>{{ tag }}</text>
							</view>
						</view>
					</template>
				</NewsCardView>
			</view>
		</view>
	</view>
</template>

<script>
	import data from "../../../data/news.json";
	import NewsCardView from "../../../components/NewsCardView.vue";
	export default {
		components: {
			NewsCardView
		},
		data() {
			return {
				newsList: [],
				isLoading: true,
				currentTab: "要闻",
				weatherData: [],
				cityInfo: {},
				formattedOuterDate: "",
				showUpdateTip: false,
				updateCount: 0,
				isFading: false,
				refreshTimer: null
			};
		},
		onLoad() {
			this.loadNewsData();
			this.fetchWeather();
			console.log("下拉刷新是否开启：", uni.getSystemInfoSync().enablePullDownRefresh);
		},
		onPageScroll(e) {
			console.log("页面滚动距离：", e.scrollTop); 
		},

		onPullDownRefresh() {
			console.log("下拉刷新触发成功！"); 
			if (this.refreshTimer) clearTimeout(this.refreshTimer);

			this.refreshTimer = setTimeout(() => {
				try {
					const newNews = this.generateNewNews();
					this.updateCount = newNews.length;
					this.newsList = [...newNews, ...this.newsList]; 
					this.showUpdateTip = true;
					this.isFading = false;

					setTimeout(() => {
						this.isFading = true;
						setTimeout(() => {
							this.showUpdateTip = false;
						}, 300);
					}, 3000);
				} catch (error) {
					console.error("下拉刷新失败：", error);
					uni.showToast({ title: "刷新失败", icon: "none" });
				} finally {
					uni.stopPullDownRefresh(); 
				}
			}, 1000);
		},
		onUnload() {
			if (this.refreshTimer) clearTimeout(this.refreshTimer);
		},
		methods: {
			loadNewsData() {
				try {
					let newsData = data.newsList.length > 0 ? data.newsList : this.getTestData();
					this.newsList = newsData.map(item => ({
						...item,
						searchTags: item.searchTags || []
					}));
					console.log("初始化新闻数量：", this.newsList.length);
				} catch (error) {
					console.error("加载失败：", error);
					this.newsList = [];
				} finally {
					this.isLoading = false;
				}
			},
			fetchWeather() {
				uni.request({
					url: "http://t.weather.sojson.com/api/weather/city/101230501",
					method: "GET",
					timeout: 10000,
					success: (res) => {
						if (res.statusCode === 200 && res.data.status === 200) {
							const forecast = res.data.data.forecast;
							this.weatherData = forecast.slice(0, 2);
							this.cityInfo = res.data.cityInfo;
							const outerDate = res.data.date;
							this.formattedOuterDate = `${outerDate.slice(0, 4)}-${outerDate.slice(4, 6)}-${outerDate.slice(6, 8)}`;
						}
					}
				});
			},
			getTestData() {
				return [
					{ nid: "news001", title: "震撼！海军千余名新兵授枪大场面", mode: 1, isTop: true, author: "环球网", comments: 2141, time: "2025-11-06", content: "近日，北部战区海军某基地举行2025年下半年入伍新兵授枪仪式...", showSearch: false, searchTags: [] },
					{ nid: "news002", title: "习近平：认真学习贯彻党的二十届四中全会精神 高标准建设海南自由贸易港", mode: 1, isTop: true, author: "央视", comments: 254125, time: "2025-11-06", content: "11月6日，中共中央总书记、国家主席、中央军委主席习近平在海南三亚...", showSearch: false, searchTags: [] },
					{ nid: "news003", title: "中国空间站首次实现“太空烧烤”", mode: 2, isTop: false, author: "新浪微博", comments: 458745, time: "2025-11-06", images: ["/static/news/news003.png"], content: "中国空间站顺利“会师”的神舟二十一号航天员乘组...", showSearch: false, searchTags: [] },
					{ nid: "news004", title: "聚焦人工智能 “互联网之光”博览会启幕", mode: 2, isTop: false, author: "新华社", comments: 4268, time: "2025-11-06", images: ["/static/news/news004.png"], content: "11月6日，2025年世界互联网大会“互联网之光”博览会在浙江乌镇开幕...", showSearch: false, searchTags: [] },
					{ nid: "news005", title: "加微信交友群，喜欢就聊，找喜欢的人", mode: 3, isTop: false, author: "我主良缘文化", comments: 0, time: "2025-11-01", images: ["/static/news/news005-1.png", "/static/news/news005-2.png", "/static/news/news005-3.png"], showSearch: false, searchTags: [] },
					{ nid: "news006", title: "2025年全国高考改革方案发布", mode: 1, isTop: false, author: "教育部", comments: 12345, time: "2025-11-05", content: "教育部今日发布2025年高考改革方案，新增...", showSearch: true, searchTags: ["高考", "改革"] },
					{ nid: "news007", title: "油价调价窗口开启 预计下调0.15元/升", mode: 1, isTop: false, author: "发改委", comments: 6789, time: "2025-11-05", content: "国内油价将于明日24时开启调价窗口...", showSearch: true, searchTags: ["油价", "下调"] },
					{ nid: "news008", title: "泉州举办海上丝绸之路国际论坛", mode: 2, isTop: false, author: "泉州晚报", comments: 3456, time: "2025-11-04", images: ["/static/news/news008.png"], content: "11月4日，海上丝绸之路国际论坛在泉州举行...", showSearch: true, searchTags: ["泉州", "海丝"] },
					{ nid: "news009", title: "新型冠状病毒疫苗研发取得新进展", mode: 1, isTop: false, author: "卫健委", comments: 78901, time: "2025-11-04", content: "国家卫健委今日宣布，新型冠状病毒疫苗研发取得新突破...", showSearch: true, searchTags: ["疫苗", "疫情"] },
					{ nid: "news010", title: "2025年亚洲杯足球赛赛程公布", mode: 2, isTop: false, author: "足协", comments: 23456, time: "2025-11-03", images: ["/static/news/news010.png"], content: "亚足联今日公布2025年亚洲杯足球赛赛程...", showSearch: true, searchTags: ["足球", "亚洲杯"] }
				];
			},
			formatCurrentDate() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, "0");
				const day = String(date.getDate()).padStart(2, "0");
				return `${year}-${month}-${day}`;
			},
			generateNewNews() {
				const titles = [
					"全国多地开启降温模式，北方部分地区跌破0℃",
					"新型国产芯片量产落地，性能较上一代提升40%",
					"2025年双十一预售开启，各大平台推出绿色消费活动",
					"世界遗产大会在泉州举办，聚焦文化遗产保护创新",
					"国足热身赛1-0小胜越南，新帅执教首秀开门红",
					"医疗保障局发布新规，12种罕见病药物纳入医保",
					"教育部：义务教育阶段课后服务全覆盖",
					"国内首条智轨快运系统正式开通",
					"垃圾分类推行五年，全国城市回收率超40%"
				];
				const newCount = Math.floor(Math.random() * 3) + 3; // 每次生成3-5条新新闻
				const newNews = [];

				for (let i = 0; i < newCount; i++) {
					const mode = Math.floor(Math.random() * 3) + 1;
					newNews.push({
						nid: `news${Date.now()}-${i}`,
						title: `【最新】${titles[Math.floor(Math.random() * titles.length)]}`,
						mode: mode,
						isTop: false,
						author: ["新华社", "人民日报", "央视新闻", "环球网"][Math.floor(Math.random() * 4)],
						comments: Math.floor(Math.random() * 2000),
						time: this.formatCurrentDate(),
						content: "这是下拉刷新新增的热点新闻，实时为您推送最新资讯...",
						images: mode === 2 || mode === 3 ? [`/static/news/news${Math.floor(Math.random() * 3) + 6}.png`] : [],
						showSearch: Math.random() > 0.5,
						searchTags: ["热点", "最新"]
					});
				}
				return newNews;
			}
		}
	};
</script>

<style scoped>
	.app-container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.top-nav {
		display: flex;
		background-color: #f0919f;
		padding: 16rpx 20rpx;
		overflow-x: auto;
		align-items: center;
	}

	.top-nav::-webkit-scrollbar {
		display: none;
	}

	.nav-item {
		color: #fff;
		font-size: 28rpx;
		margin-right: 30rpx;
		padding-bottom: 8rpx;
		white-space: nowrap;
	}

	.nav-item.active {
		border-bottom: 2rpx solid #fff;
		font-weight: bold;
	}

	.weather-search {
		display: flex;
		align-items: center;
		background-color: #e06b85;
		padding: 16rpx 20rpx;
		color: #fff;
		flex-wrap: wrap;
		gap: 12rpx;
	}

	.weather-info {
		font-size: 26rpx;
		line-height: 1.5;
		flex: 1;
		min-width: 200rpx;
	}

	.search-box {
		background-color: #fff;
		border-radius: 30rpx;
		padding: 12rpx 20rpx;
		font-size: 24rpx;
		color: #aaa;
		min-width: 280rpx;
	}

	.news-list {
		flex: 1;
		padding: 16rpx;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
	}

	.list-item {
		padding: 16rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.loading {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 50rpx;
		color: #666;
		font-size: 28rpx;
	}

	.empty {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.update-tip {
		background-color: #e74b82;
		color: #fff;
		padding: 12rpx 20rpx;
		font-size: 28rpx;
		text-align: center;
		transition: opacity 0.3s ease, transform 0.3s ease;
		opacity: 1;
		transform: translateY(0);
		margin: 16rpx;
		border-radius: 12rpx;
	}

	.update-tip.fade-out {
		opacity: 0;
		transform: translateY(-20rpx);
	}

	.slot-content {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 10rpx 20rpx;
		color: #6699ff;
		font-size: 26rpx;
		flex-wrap: wrap;
	}

	.search-label {
		margin-right: 10rpx;
		font-weight: 500;
	}

	.search-tag {
		margin: 0 8rpx 8rpx;
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		border: 1px solid #ccdfff;
		background-color: #f0f7ff;
	}
</style>